package org.example.order.service.impl;

import cn.lingyangwl.framework.tool.core.exception.BizException;
import io.seata.spring.annotation.GlobalTransactional;
import org.example.order.mapper.OrderMapper;
import org.example.order.model.entity.OrderDO;
import org.example.order.service.AccountService;
import org.example.order.service.OrderService;
import org.example.order.service.StorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * @author shenguangyang
 */
@Service
public class OrderServiceImpl implements OrderService {
    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Resource
    OrderMapper orderMapper;

    @Resource
    AccountService accountService;

    @Resource
    StorageService storageService;

    @Override
    @Transactional
    @GlobalTransactional
    public void create(OrderDO orderDO) {
        log.info("开始创建订单");
        orderMapper.create(orderDO);

        // 扣减库存
        log.info("============ 订单微服务 调用库存微服务，减库存 start ==============");
        storageService.decrease(orderDO.getProductId(), orderDO.getCount());
        log.info("============ 订单微服务 调用库存微服务，减库存 end  ==============");

        // 扣减账户余额
        log.info("============ 订单微服务 调用账户微服务，减余额 start ==============");
        accountService.decrease(orderDO.getUserId(), orderDO.getMoney());
        log.info("============ 订单微服务 调用账户微服务，减余额 end ==============");

        // 修改订单状态
        // 扣减账户余额
        log.info("============ 修改订单状态 start ==============");
        orderMapper.update(orderDO.getUserId(),0);
        log.info("============ 修改订单状态 end ==============");

        // 模拟下单服务异常, 账户和库存服务回滚现象
        if (orderDO.getUserId().compareTo(3L) == 0) {
            throw new BizException("下单异常");
        }
        if (orderDO.getMoney().compareTo(BigDecimal.valueOf(300)) == 0) {
            // 模拟超时
            throw new BizException("下单异常");
        }
        log.info("下单结束了");
    }
}
